<?php
/**
 * 考勤管理控制器
 * @author ZhouYP
 **/
namespace Admin\Controller;
use Common\Controller\AuditbaseController;
class AttendanceController extends AuditbaseController{
	protected $deal_model;

	public function _initialize() {
		parent::_initialize();
		$this->deal_model = D("Common/Attendance");
		
		$this->check = array('code');
	}

	/**
     *  主页
     */
	public function index(){
		$where_date = $_POST['work_date'] == NULL ? date("Y-m") : $_POST['work_date'];
        // 当前登录人
        $adminId = session('ADMIN_ID');
		$deptId = session('deptid');
        $where_date_start = $where_date.'-01';
        $where_date_end = date('Y-m-d', strtotime("$where_date_start +1 month -1 day"));
		$sql = "SELECT a.id,a.realname,a.is_deleted,work_date,COUNT(tobe) AS ytobe,COUNT(really) AS sreally,COUNT(absenteeism) AS ab,d.department_name
				FROM hzzy_attendance a
				LEFT JOIN hzzy_users u ON a.user_id = u.id
				LEFT JOIN hzzy_department d ON u.department_id = d.id
				WHERE work_date > '".$where_date_start."' AND work_date < '".$where_date_end."'
					AND (
						-- 超级管理员
						".$adminId." = 1
						-- 部门相同
						OR d.id = ".$deptId."
						-- 部门级别高
						OR (SELECT department_role FROM hzzy_department WHERE id = ".$deptId.") < d.department_role
					)
				GROUP BY realname,a.department_name
				ORDER BY a.add_time";
        $results = $this->deal_model->query($sql);
		
        $this->assign("results", $results);
		$this->assign("query", $where_date);
		
        $this->display();
	}

	/**
     *  添加
     */
	public function add(){
		$this->display();
	}
	public function add_post(){
		if(IS_POST){
			$url = U(CONTROLLER_NAME.'/'.(I('get.fun') != NULL ? I('get.fun') : 'index'));
			if ($this->deal_model->create()!==false) {
					$result = $this->import();
					if($result == true){
						$this->success("添加成功！", $url);
					}
					else{
						$this->error("添加失败,Excel格式不正确！");
					}
			} else {
				$this->error($this->deal_model->getError());
			}
		}
	}
	####详情
	public function detailPage($where_date,$name=''){
        $eq = array(
            "eq" => "=",
            "neq" => "!=",
            "gt" => ">",
            "egt" => ">=",
            "lt" => "<",
            "elt" => "<=",
            "like" => "LIKE"
        ); 
        // 当前登录人
        $adminId = session('ADMIN_ID');
        $where_date_start =$where_date.'-01';
        $where_date_end = date('Y-m-d', strtotime("$where_date_start +1 month -1 day"));
        //$where_str = "work_date>'".$where_date_start."' and work_date<='".$where_date_end.' ';
        //echo $where_date_start;
        //echo $where_date_end;
        //echo $where_date;
        $where_str=" TIMESTAMPDIFF(MONTH,
        ADDDATE(LAST_DAY(SUBDATE(work_date, INTERVAL 1 MONTH)), 1),
        ADDDATE(LAST_DAY(SUBDATE('$where_date', INTERVAL 1 MONTH)), 1) )=0 ";
        if($name!=''){
        	$where_str .=" and realname ='".$name."'";
        }

        $results = $this->deal_model
            ->where($where_str)
            //->where("TIMESTAMPDIFF(MONTH,work_date,'$where_date_start')=0")
            //->group("realname,department_name")
            ->order("work_date")
            ->select();
        $this->assign("results",$results);
        $this->display();
    }
    /**
     *  删除 buyong
     */
	public function delete(){
	    $id = I('get.id', 0, 'intval');
		if(!$id){
			$this->error("请选择要删除的数据！");
		}
		$data = array(
			'id'	=> $id,
			'is_deleted' => 1
		);
		if ($this->deal_model->save($data) !== false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}
	/**
     *  详情页
     */
	public function view(){
		$name=$_GET['name'];
		$where_date=$_GET['work_date'];
		//var_dump($_GET);
		$this->detailPage($where_date,$name);
	}
	/*
	 * 导入数据
	 * 工程项目报价汇总表  
	 **/
	public function import(){
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel.php';
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel5.php';// 用于其他低版本xls 
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel2007.php';// 用于 excel-2007 格式
		  
		$filePath = $_POST['attachment_1'];
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 

		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){
				return '文件读取失败'; 
			} 
		}
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		//验证录入的文件格式是否正确
		$dataArray = $PHPExcel->getSheet(0)->toArray();
		//var_dump($dataArray);
		$datas = array(
			0 => "序号",
			1 => "考勤号码",
			2 => "自定义编号",
			3 => "姓名",
			4 => "是否智能排班",
			5 => "日期"
		);
		$length = count($datas);
		$aa=true;
		for($i = 0;$i< $length;$i++){
			$colName =str_replace(" ","",str_replace("\n", "", $dataArray[0][$i]));
			if($datas[$i] != $colName){
				$aa = false;
				//echo ("文件格式不一致，".$colName."执行了这里");
				break;
			}
		}
		if(!$aa){
			return false;
		}

		//验证是否重复录入
		$attendance=$this->deal_model->select();
		// 保存数组
		$savedata = $this->saveData();
		$usermodel = M('users');
		for($i = 0; $i < count($sheetNames); $i++){
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			$allColumn = $currentSheet->getHighestColumn();

			$shijian="1970-01-01";
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			for($currentRow = 2; $currentRow <= $allRow; $currentRow++){
				$savedata['realname']	= $currentSheet->getCell("D".$currentRow)->getValue();
				$userinfo = $usermodel->field("id")->where("real_name = '".$savedata['realname']."'")->find();
				$savedata['user_id'] = $userinfo['id'] !== null ? $userinfo['id'] : 0;
				$savedata['work_date']	= $currentSheet->getCell("F".$currentRow)->getValue();
        		$savedata['work_date'] = is_numeric ($savedata['work_date']) ? date("Y-m-d",($savedata['work_date']-25569)*86400) : $currentSheet->getCell("F".$currentRow)->getValue();
        		$shijian= $savedata['work_date'];
				$savedata['check_in_time']	=NULL;
				$check_in_time = $currentSheet->getCell("J".$currentRow)->getValue();
				if($check_in_time){
					$savedata['check_in_time']	= $currentSheet->getCell("J".$currentRow)->getValue();
				}
				$savedata['check_out_time']	=NULL;
				$check_out_time = $currentSheet->getCell("J".$currentRow)->getValue();
				if($check_in_time){
					$savedata['check_out_time']	= $currentSheet->getCell("K".$currentRow)->getValue();
				}
				$savedata['arrive_late'] =NULL;
				if($check_in_time){
					$savedata['arrive_late']	= $currentSheet->getCell("N".$currentRow)->getValue();
				}
				$savedata['leave_earlier'] =NULL;
				if($check_in_time){
					$savedata['leave_earlier']	= $currentSheet->getCell("O".$currentRow)->getValue();
				}
				
				$savedata['absenteeism']=NULL;
				$savedata['tobe']=NULL;
				$savedata['really']=NULL;

				$sss=$currentSheet->getCell("P".$currentRow)->getValue();
				if($sss=='True'){
					$savedata['absenteeism']	= $currentSheet->getCell("P".$currentRow)->getValue();
				}

				$ddd=$currentSheet->getCell("L".$currentRow)->getValue();
				if($ddd!=''){
					$savedata['tobe']=$currentSheet->getCell("L".$currentRow)->getValue();
				}

				$fff=$currentSheet->getCell("M".$currentRow)->getValue();
				if($fff!=''){
					$savedata['really']=$fff;					
				}
				$savedata['work_overtime']	=Null;
				$work_overtime=$currentSheet->getCell("Q".$currentRow)->getValue();
				if($work_overtime){
					$savedata['work_overtime']	= $work_overtime;
				}
				$savedata['work_hours']	=Null;
				$work_hours =$currentSheet->getCell("R".$currentRow)->getValue();
				if($work_hours){
					$savedata['work_hours']	= $work_hours;
				}
				$savedata['department_name']	= $currentSheet->getCell("V".$currentRow)->getValue();
				$savedata['attendance_time']	=Null;
				$attendance_time=$currentSheet->getCell("Z".$currentRow)->getValue();
				if($attendance_time){
					$savedata['attendance_time']	= $attendance_time;
				}

				if($currentRow == 2){
				
					$this->deal_model->where(" TIMESTAMPDIFF(MONTH,
        					ADDDATE(LAST_DAY(SUBDATE(work_date, INTERVAL 1 MONTH)), 1),
        					ADDDATE(LAST_DAY(SUBDATE('$shijian', INTERVAL 1 MONTH)), 1) )=0 ")->delete();
				}	
				if($savedata['realname']!=""){
					// 保存数据
					
					$this->deal_model->add($savedata);
				}
			}
		}
		return true;
		// 导入完成 删除文件
		unlink($filePath);
	}
	
}


?>